import netCDF4 as nc
from pynctools import pynctools

def pyncwrite(fout,var,mode='w'):
   '''
   usage pyncwrite(file, var, mode='w')
        
    file   = filename
    var    = variable name
    mode   = file mode to be opened (default: 'w')
             'w'  for write mode
             'a'  for append mode
    
    Author: Vihang Bhatt 
    Email : bhatt.vihang@gmail.com 
   '''
   if var.__module__ is not pynctools.__module__:
      print var.__module__
      print 'var.name is not pynctoos object'
      print 'The variable should be pynctools object'
      raise

   fid=nc.Dataset(fout,mode)

   if 'dimensions' in dir(var) and var.dimensions is not None:
      if len(var.dimensions) != len(var.data.shape):
         print 'error: check data file again'
         print len(var.dimensions), len(var.data.shape)
         return
      
      i=0
      for dim in var.dimensions:
         if dim not in fid.dimensions.keys():
            fid.createDimension(dim,var.data.shape[i])
         i+=1
   else:
      var.dimensions=()
      
   
   if 'FillValue' in dir(var):
      fid.createVariable(var.name,'f8',var.dimensions,fill_value=var.FillValue)
   else:
      fid.createVariable(var.name,'f8',var.dimensions)
      
   for attr in dir(var):
       if attr[0] is not '_':
          if attr is 'data':
             fid.variables[var.name][:]=var.data
          elif attr is not 'dimensions' and attr is not 'shape' and    \
               attr is not '_FillValue' and attr is not 'name' and     \
               attr is not 'FillValue' :
             setattr(fid.variables[var.name], attr , eval( 'var.' + attr ) )
         
   fid.close
